package cn.iocoder.yudao.module.scrm.service.customer;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.scrm.controller.admin.customer.vo.CustomerPoolConfigSaveReqVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.CustomerPoolConfigDO;
import cn.iocoder.yudao.module.scrm.dal.mysql.customer.CustomerPoolConfigMapper;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.starter.annotation.LogRecord;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Objects;

import static cn.iocoder.yudao.module.scrm.enums.LogRecordConstants.*;


/**
 * 客户公海配置 Service 实现类
 *
 * @author Wanwan
 */
@Service
@Validated
public class CustomerPoolConfigServiceImpl implements CustomerPoolConfigService {

    @Resource
    private CustomerPoolConfigMapper customerPoolConfigMapper;

    @Override
    public CustomerPoolConfigDO getCustomerPoolConfig() {
        return customerPoolConfigMapper.selectOne();
    }

    @Override
    @LogRecord(type = SCRM_CUSTOMER_POOL_CONFIG_TYPE, subType = SCRM_CUSTOMER_POOL_CONFIG_SUB_TYPE, bizNo = "{{#poolConfigId}}",
            success = SCRM_CUSTOMER_POOL_CONFIG_SUCCESS)
    public void saveCustomerPoolConfig(CustomerPoolConfigSaveReqVO saveReqVO) {
        // 1. 存在，则进行更新
        CustomerPoolConfigDO dbConfig = getCustomerPoolConfig();
        CustomerPoolConfigDO poolConfig = BeanUtils.toBean(saveReqVO, CustomerPoolConfigDO.class);
        if (Objects.nonNull(dbConfig)) {
            customerPoolConfigMapper.updateById(poolConfig.setId(dbConfig.getId()));
            // 记录操作日志上下文
            LogRecordContext.putVariable("isPoolConfigUpdate", Boolean.TRUE);
            LogRecordContext.putVariable("poolConfigId", poolConfig.getId());
            return;
        }

        // 2. 不存在，则进行插入
        customerPoolConfigMapper.insert(poolConfig);
        // 记录操作日志上下文
        LogRecordContext.putVariable("isPoolConfigUpdate", Boolean.FALSE);
        LogRecordContext.putVariable("poolConfigId", poolConfig.getId());
    }

}
